**********************************************************************************************
**********************************************************************************************
*POLITICAL SETTLEMENTS DATAST  
*Replication Do File
**********************************************************************************************
**********************************************************************************************

*version 17.0
clear all
set more off

*Replace "YOUR WORKING DIRECTORY" with your working directory path in the do-file (e.g. using "ctrl+h")

*Install packages required to reproduce all graphs
net install palettes, replace from(https://raw.githubusercontent.com/benjann/palettes/master/)
net install colrspace, replace from(https://raw.githubusercontent.com/benjann/colrspace/master/)
net install cleanplots, from("https://tdmize.github.io/data/cleanplots")
graph set window fontface "Times New Roman"
ssc install schemepack, replace
ssc install colrspace, replace
ssc install palettes, replace
ssc install labutil, replace
net describe pr0041_4, from(http://www.stata-journal.com/software/sj21-3)
net install pr0041_4 
ssc install violinplot, replace
ssc install dstat, replace
ssc install moremata, replace


**********************************************************************************************
*MANUSCRIPT
**********************************************************************************************


**********************************************************************************************
**# Figure 1

use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
keep if cname_psd != ""
collapse q1_populationshare_clb, by(cabbrev_pwt leadername_number)
by cabbrev_pwt: gen Nr = [_n]
by cabbrev_pwt: replace Nr = [_N]
collapse Nr, by(cabbrev_pwt)

rename cabbrev_pwt ADM0_A3
merge m:m ADM0_A3 using "YOUR WORKING DIRECTORY\GeoMap\worlddata2.dta"
egen cname_psdID = group(ADM0_A3)

spmap Nr using "YOUR WORKING DIRECTORY\GeoMap\worldcoor.dta" if year == 1970 & SOVEREIGNT!="Antarctica", id(id) fcolor(YlGnBu) ndfcolor(dimgray) /// 
  clmethod(custom) clbreaks(0 5 10 15 20 27)  title("Number of Political Periods per Country") legtitle("") legcount  legend(size(medium))   legstyle(2) 
 gr_edit .legend.plotregion1.DragBy -1.445879117999281 98.42802178795243
   graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Figure 1.pdf", replace


**********************************************************************************************
**# Table 2
  use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
  
cd "YOUR WORKING DIRECTORY\Graphs_Tables"
*Section 1 & 3
eststo clear
estpost corr  VDEM_v2regsupgroupssize EPR_RulColsize VDEM_e_polity2 gfw2018_personalism q1_populationshare_lb q2_power_lb q14_polmakingconcent , matrix
eststo corrtr
esttab using "Sect1PowerVdemTest.rtf", replace b(2) lines not noobs nonum unstack compress star(a 0.10 b 0.05 c 0.01) nogap onecell label
eststo clear

*Section 2
eststo clear
estpost corr VDEM_v2csreprss VDEM_v2exl_legitideol VDEM_v2xnp_client VDEM_v2pepwrses q10_demlegitlead_ob q10_violrepresslead_ob  q11_ideologlegitfoll_lb q10_clientmatcooptlead_lb q12_crossblocdistri_lb q13_withinblocdistri_lb, matrix
eststo corrtr
esttab using "Sect2PowerVdemTest.rtf", replace b(2) lines not noobs nonum unstack compress star(a 0.10 b 0.05 c 0.01) nogap onecell label
eststo clear

*Section 4 & 5
eststo clear
estpost corr  VDEM_v2regoppgroupsact_6  VDEM_v2regoppgroups_9 VDEM_v2regsupgroups_3 VDEM_v2clstown  q18_polthreat_ethnoregrel q18_polthreat_urbansub q21_firmpower, matrix
eststo corrtr
esttab using "Sect4_5VdemTest.rtf", replace b(2) lines not noobs nonum unstack compress star(a 0.10 b 0.05 c 0.01) nogap onecell label
eststo clear

*Thereafter combined manually into one table.


**********************************************************************************************
**# Figure 2
 *(a)
 use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions", clear
gen SumCount = 1
egen totalsum = sum(SumCount)
gen perc = (SumC/total)*100
collapse q1_populationshare_*b  q11_demlegitfoll_*b	 q10_violrepresslead_*b	q12_crossblocdistri_*b	 q2_power_*b (sum) SumCount, by(QOG_chga_hinst)
drop if QOG_ == . | QOG == 99
label define QOG_chga_hinst_new 0 "Parliament. Dem." 1 "Semi-Presidential Dem." 2 "Presidential Dem." 3 "Civilian Dictator." 4 "Military Dictator." 5  "Royal Dictator." 
label values QOG_chga_hinst QOG_chga_hinst_new
gen axis = _n

labmask axis, values(QOG) decode

cd "YOUR WORKING DIRECTORY\Graphs_Tables"

graph dot q2_power_*b, over(axis, label(angle(45) labsize(4))) ylabel(1(1)5, grid glcolor(gs15))   bgcolor(white) graphregion(color(white)) title("(a)", size(4.5) color(black) margin(b=4)) ytitle("Relative Power", size(4)) legend(row(1) label(1 "LB") label(2 "CLB") label(3 "OB") margin(medlarge)) marker(1, mcolor(dknavy) msymbol(S)) marker(2, mcolor(eltblue) msymbol(T)) marker(3, mcolor(cranberry) msymbol(O)) saving(g1, replace) vertical dots(mcolor(none))  exclude0 
 
graph save "Graph" "YOUR WORKING DIRECTORY\Graphs_Tables\g1.gph", replace

 *(b)
 use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions", clear
 
cd "YOUR WORKING DIRECTORY\Graphs_Tables"

  twoway kdensity q2_power_lb if QOG_chga_hinst == 0, xtitle("LB Power", size(4)) ytitle(Density, size(4)) ///
 title((b), size(4.5) span)  lcolor(blue) lwidth(medthick)  lpattern(dot) || ///
     kdensity q2_power_lb if QOG_chga_hinst == 3, lcolor(orange) lwidth(medthick) lpattern(longdash) || ///
  kdensity q2_power_lb if QOG_chga_hinst == 1, lcolor(ebblue) lwidth(medthick) lpattern(shortdash) || ///
   kdensity q2_power_lb if QOG_chga_hinst == 4, lcolor(red) lwidth(medthick) lpattern(longdash_dot) || ///
   kdensity q2_power_lb if QOG_chga_hinst == 2, lcolor(cyan) lwidth(medthick) lpattern(dash) || ///
 kdensity q2_power_lb if QOG_chga_hinst == 5, lcolor(maroon) lwidth(medthick) lpattern(solid)  ///
 legend(order(1 "Parliament. Dem."  2 "Civilian Dictator." 3 "Semi-Presidential Dem." 4 "Military Dictator." 5 "Presidential Dem."  6  "Royal Dictator.") size(4) col(1) ring(O)) bgcolor(white) graphregion(color(white)) saving(g2, replace) 
  
 graph combine "g1" "g2"
 
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Figure 2.pdf", replace 
	

**********************************************************************************************
**# Figure 3
 use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions", clear
sort cname_psd year
drop if year < 1950
rename q14_polmakingconcent PolicyConcentration
rename gfw2018_personalism personalism
label variable personalism "Personalism Index (Geddes et al. 2018)"
sort ccode_cow year
 replace PolicyConcentration = PolicyConcentration/4
 replace q2_power_lb = q2_power_lb/5
 
 keep if inlist(cname_psd, "China", "Côte d'Ivoire", "Malaysia", "South Africa") 

 xtline personalism PolicyConcentration q2_power_lb, cmissing(n n n)  t(year) i(cname_psd) ylabel(0(0.25)1) xlabel(1960(10)2020, grid) byopt(note("") graphregion(color(white))) legend(size(3.1) col(1)) subtitle(, fcolor(gs16) lcolor(black)) xtitle(Year, size(3))  lpattern(shortdash longdash solid) 
    graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Figure 3.pdf", replace 
 


**********************************************************************************************
**# Figure 4
 use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
 collapse q11_clientmatcooptfoll_lb q11_ideologlegitfoll_lb  q11_violrepressfoll_ob q11_demlegitfoll_ob  q18_polthreat_ruralsub q18_polthreat_ruraldom q18_polthreat_urbansub q18_polthreat_urbandom q18_polthreat_ethnoregrel q18_polthreat_military, by(year)
drop if year > 2018 | year < 1950

line q11_clientmatcooptfoll_lb q11_ideologlegitfoll_lb  q11_violrepressfoll_ob q11_demlegitfoll_ob  year, graphregion(fcolor(white)) legend(col(1) label(1 "Clientelistic material cooptation of LB followers") label(2 "Ideological Legitimation for LB followers") label(3 "Violent repression of OB followers")  label(4 "Democratic legitimation for OB followers")) lcolor(black  blue red green) lpattern(dash shortdash solid  longdash) xlabel(1950(10)2020) ytitle(Strategic importance)

graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Figure 4.pdf", replace 
	   
	   
**********************************************************************************************
**# Figure 5
line  q18_polthreat_ruralsub q18_polthreat_ruraldom q18_polthreat_urbansub q18_polthreat_urbandom q18_polthreat_ethnoregrel q18_polthreat_military year, graphregion(fcolor(white)) legend(row(3) label(1 "Rural subordinate classes") label(2 "Rural dominant classes") label(3 "Urban subordinate classes") label(4 "Urban dominant classes") label(5 "Ethnic, regional, or religious groups") label(6 "The military")) lcolor(green green purple purple blue red) lpattern(shortdash longdash dot dash longdash_dot solid) xlabel(1950(10)2020)  lwidth(medium medium medium medium medium medium) ytitle(Threat level)

    graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Figure 5.pdf", replace 

	
	

	
**********************************************************************************************
**#ONLINE APPENDIX
**********************************************************************************************
 
 **********************************************************************************************
**# Table 2
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
* For EPR only look at periods were Ethnicity was relevant.
replace EPR_RulColsize = . if EPR_IRR > 0
encode leadername_archigos, gen(archigos_num)
foreach v of varlist archigos_num VDEM_v2regsupgroupssize q1_populationshare_lb VDEM_v2regoppgroupssize q1_populationshare_clb gfw2018_personalism q1_populationshare_ob q2_power_lb q2_power_clb q2_power_ob x_powerconcentration_add GandhiS_xhatmean_nor VDEM_e_polity2 QOG_ht_regtype QOG_ht_regtype1 QOG_bmr_dem VDEM_v2xpe_exlecon VDEM_v2x_regime VDEM_e_boix_regime QOG_chga_hinst VDEM_e_chga_demo EPR_RulColsize  {
keep if cname_psd != ""
sort cname_psd year
gen byte begin_`v' = `v' != `v'[_n-1]
gen spell_`v' = sum(begin_`v')
by spell_`v' (year), sort: gen length_`v' = year[_N] - year[1] + 1
replace  length_`v'  = . if  `v'  == .
collapse  length_`v' , by(spell_`v')
collapse  length_`v'
gen v = 1
save "YOUR WORKING DIRECTORY\Graphs_Tables\Time Spell Comparison\length_`v'.dta", replace
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
}

cd "YOUR WORKING DIRECTORY\Graphs_Tables\Time Spell Comparison"
clear
merge using `: dir . files "*.dta"'
drop _m* v
rename length_* *
xpose, clear varname
rename _v Variable
rename v1 AverageSpellLength
order V A
sort A

replace Variable = "Personalism index (Geddes et al. 2018)" if Variable == "gfw2018_personalism"
replace Variable = "Regime support groups size (Coppedge et al 2022)" if Variable == "VDEM_v2regsupgroupssize"
replace Variable = "Population share (in %) of LB (PolSett Dataset)" if Variable == "q1_populationshare_lb"
replace Variable = "Polity revised combined score (Polity 5 (Marshall and Jaggers 2020))" if Variable == "VDEM_e_polity2"
replace Variable = "Authorian Regime Type (Hadenius/Teorell 2007)" if Variable == "QOG_ht_regtype"
replace Variable = "Regimes of the world (Lührmann et al 2018) " if Variable == "VDEM_v2x_regime"
replace Variable = "Regime Institutions (Cheibub et al 2010)" if Variable == "QOG_chga_hinst"
replace Variable = "Ethno-political constellation (Vogt et al 2015)" if Variable == "EPR_RulColsize"
replace Variable = "Democracy (Boix et al 2012)" if Variable == "VDEM_e_boix_regime"
replace Variable = "Democracy (Cheibub et al 2010)" if Variable == "VDEM_e_chga_demo"


export excel using "YOUR WORKING DIRECTORY\Graphs_Tables\Time Spell Comparison.xls", firstrow(variables) replace
 
 
 
 **********************************************************************************************
**# Figure 1

*RSD PER QUESTION
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
collapse *_rsd
xpose, clear varname

gen numeric_var1 = regexs(2) if regexm(_v, "^([^0-9]*)([0-9]+)([^0-9]*)$")
destring, replace
collapse v1, by(num)
gsort -v
rename v1 RSD
save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\RSD_perQuestionNumber.dta", replace

*CONFIDENCE PER QUESTION
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
collapse q1_confidence q2_confidence q3_confidence q4_confidence q5_confidence q6_confidence q7_confidence q8_confidence q9_confidence q10_confidence q11_confidence q12_confidence q13_confidence q14_confidence q15_confidence q16_confidence q17_confidence q18_confidence q19_confidence q20_confidence q21_confidence 
xpose, clear varname

gen numeric_var1 = regexs(2) if regexm(_v, "^([^0-9]*)([0-9]+)([^0-9]*)$")
destring, replace
collapse v1, by(num)
gsort -v
rename v1 Confidence
save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Confidence_perQuestionNumber.dta", replace

**Merge Confidence and RSD per question into one table

use "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Confidence_perQuestionNumber.dta", clear

merge 1:1 numeric_var1 using "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\RSD_perQuestionNumber.dta"
drop _merge


rename numeric Question

gen Question1 = Question - 0.2
gen Question2 = Question + 0.2

graph twoway bar Confidence Question , color(black) yaxis(1) barw(0.4) ytitle("Average Confidence", axis(1) size(*.9)) ylabel(1(0.5)4, axis(1) labsize(*.9) nogrid)  ysc(titlegap(2)) graphregion(fcolor(white))|| scatter RSD Question , fcolor(gray) lcolor(black) yaxis(2) ylabel(0(0.1)1, axis(2) labsize(*.9)) ytitle(" " "Average RSD", axis(2) size(*.9)) legend(order(1 "Confidence" 2 "Relative Standard Deviation") position(1) ring(0) rows(2) size(*.9) region(lcolor(white)))  xtitle("Question", size(*.9)) xlabel(1(1)21,  valuelabel labsize(*.8) angle(45) ) 
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Figure 1.pdf", replace



 **********************************************************************************************
**# Figure 2
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
collapse *_rsd *_confidence, by(cname_psd)
drop if cname== ""
egen RSD_Country_mean = rowmean(*_rsd)
egen Confidence_Country_mean = rowmean(*_confidence)

keep cname_psd RSD_Country_mean Confidence_Country_mean

gen Question = _n
labmask Question, values(cname)

graph twoway bar Confidence Question , color(black) yaxis(1) barw(0.4) ytitle("Average Confidence", axis(1) size(*.9)) ylabel(1(0.5)4, axis(1) labsize(*.9) nogrid)  ysc(titlegap(2)) graphregion(fcolor(white))|| scatter RSD Question , fcolor(gray) lcolor(black) yaxis(2) ylabel(0(0.1)1, axis(2) labsize(*.9)) ytitle(" " "Average RSD", axis(2) size(*.9)) legend(order(1 "Confidence" 2 "Relative Standard Deviation") position(1) ring(0) rows(2) size(*.9) region(lcolor(white))) aspectratio(0.6)  xtitle("") xlabel(1(1)44,  valuelabel labsize(*.55) angle(45) ) 
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Figure 2.pdf", replace



 **********************************************************************************************
**# Figure 3
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
collapse *_rsd *_confidence, by(year)
egen RSD_Country_mean = rowmean(*_rsd)
egen Confidence_Country_mean = rowmean(*_confidence)
keep year RSD_Country_mean Confidence_Country_mean
gen Question = _n
labmask Question, values(year)
graph twoway bar Confidence Question , color(black) yaxis(1) barw(0.4) ytitle("Average Confidence", axis(1) size(*.9)) ylabel(1(0.5)4, axis(1) labsize(*.9) nogrid)  ysc(titlegap(2)) graphregion(fcolor(white))|| scatter RSD Question , fcolor(gray) lcolor(black) yaxis(2) ylabel(0(0.1)1, axis(2) labsize(*.9)) ytitle(" " "Average RSD", axis(2) size(*.9)) legend(order(1 "Confidence" 2 "Relative Standard Deviation") position(1) ring(0) rows(2) size(*.9) region(lcolor(white))) aspectratio(0.6)  xtitle("") xlabel(1(10)74,  valuelabel labsize(*.55) angle(45) ) 
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Figure 3.pdf", replace


 **********************************************************************************************
**# Figure 4


*****Try making a histogramm for all observations
*First try to get all observations into one variable
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
foreach v of varlist *_rsd{
keep `v'
rename `v' x
drop if x ==.
save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Histogramm input\test`v'", replace
use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
}

clear
**# Bookmark #1

cd "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Histogramm input"
local fnames: dir "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Histogramm input" files "*"
foreach file of local fnames{
        append using "`file'"
        }

save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Histogramm input\AllObservationsCombinedForHistogram.dta", replace

histogram x, percent color(gs10) lcolor(gs3) width(0.05) xlabel(0(0.5)3.5)  xtitle("Relative Standard Deviation", size(*.9)) graphregion(color(white))
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Figure 4.pdf", replace


 **********************************************************************************************
**# Figure 5

use "YOUR WORKING DIRECTORY\Political Settlements Replication Dataset_International Interactions.dta", clear
 keep year cname_psd q1_populationshare_lb q1_populationshare_clb q1_populationshare_ob q2_power_lb q2_power_clb q2_power_ob q3_clbsplit q4_objoin q7_powerlesspercentage_lb q7_powerlesspercentage_clb q7_powerlesspercentage_ob q8_hierarchy_lb q8_hierarchy_clb q8_hierarchy_ob q9_cohesiveness_lb q9_cohesiveness_clb q9_cohesiveness_ob q10_violrepresslead_lb q10_nonviolrepresslead_lb q10_clientmatcooptlead_lb q10_clientnonmatlead_lb q10_progmatlegitlead_lb q10_ideologlegitlead_lb q10_demlegitlead_lb q10_violrepresslead_clb q10_nonviolrepresslead_clb q10_clientmatcooptlead_clb q10_clientnonmatlead_clb q10_progmatlegitlead_clb q10_ideologlegitlead_clb q10_demlegitlead_clb q10_violrepresslead_ob q10_nonviolrepresslead_ob q10_clientmatcooptlead_ob q10_clientnonmatlead_ob q10_progmatlegitlead_ob q10_ideologlegitlead_ob q10_demlegitlead_ob q11_violrepressfoll_lb q11_nonviolrepressfoll_lb q11_clientmatcooptfoll_lb q11_clientnonmatfoll_lb q11_progmatlegitfoll_lb q11_ideologlegitfoll_lb q11_demlegitfoll_lb q11_violrepressfoll_clb q11_nonviolrepressfoll_clb q11_clientmatcooptfoll_clb q11_clientnonmatfoll_clb q11_progmatlegitfoll_clb q11_ideologlegitfoll_clb q11_demlegitfoll_clb q11_violrepressfoll_ob q11_nonviolrepressfoll_ob q11_clientmatcooptfoll_ob q11_clientnonmatfoll_ob q11_progmatlegitfoll_ob q11_ideologlegitfoll_ob q11_demlegitfoll_ob q12_crossblocdistri_lb q12_crossblocdistri_clb q12_crossblocdistri_ob q13_withinblocdistri_lb q13_withinblocdistri_clb q13_withinblocdistri_ob q14_polmakingconcent q15_polimplemconcent q16_formilsupport q17_forfintechsupport q18_polthreat_ruralsub q18_polthreat_ruraldom q18_polthreat_urbansub q18_polthreat_urbandom q18_polthreat_ethnoregrel q18_polthreat_exileoppos q18_polthreat_military q18_polthreat_neighbcntry q18_polthreat_nonneighbcntry q19_phythreat_ruralsub q19_phythreat_ruraldom q19_phythreat_urbansub q19_phythreat_urbandom q19_phythreat_ethnoregrel q19_phythreat_exileoppos q19_phythreat_military q19_phythreat_neighbcntry q19_phythreat_nonneighbcntry q20_firmcapapilities q21_firmpower
quietly pwcorr _all
matrix define C = r(C)
drop _all
svmat double C, names(col)
matrix drop C
drop year
drop in 1
save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Correlation Histogram\CorrelationHistInput.dta", replace

foreach v of varlist q* {
keep `v'
rename `v' x
drop if x ==1
save "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Correlation Histogram\Correlation Input\test`v'", replace
use "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Correlation Histogram\CorrelationHistInput.dta", clear
}

clear
**# Bookmark #1

cd "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Correlation Histogram\Correlation Input"
local fnames: dir "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Correlation Histogram\Correlation Input" files "*"
foreach file of local fnames{
        append using "`file'"
        }
		
drop if x > 0.99
replace x=x*(-1) if x<0

sum x, det
histogram x, percent color(gs10) lcolor(gs3) width(0.05) xlabel(0(0.1)1)  xtitle("Correlation coefficient", size(*.9)) graphregion(color(white))
graph export "YOUR WORKING DIRECTORY\Graphs_Tables\Confidence_RSD\Figure 5.pdf", replace
